use std::io::Cursor;
use std::ops::IndexMut;

use image::{DynamicImage, GenericImage, GenericImageView, GrayImage, Rgb, Rgba, RgbaImage, RgbImage};

fn main() {
    /*// 加载 JPEG 图像
    let img = image::open("overexposure.jpg").expect("Failed to open image").to_luma8();
    // 调整亮度
    let brightened_img = adjust_brightness(&img, 50); // 50 是调整的亮度值，可以根据需要调整
    // 保存修改后的图像
    brightened_img.save("output.jpg").expect("Failed to save image");*/

    // 加载 JPEG 图像
    let img = image::open("overexposure.jpg").expect("Failed to open image");
    // 调整亮度
    let brightened_img = adjust_brightness0(&img); // 50 是调整的亮度值，可以根据需要调整
    // 保存修改后的图像
    brightened_img.save("output.jpg").expect("Failed to save image");
}

// 调整亮度的函数
fn adjust_brightness0(img: &DynamicImage) -> DynamicImage {
    // 创建一个新的图像，用于存储调整后的结果
    // let mut new_img = img.clone();

    let mut new_img = RgbaImage::new(img.width(), img.height());

    // 计算图像的平均亮度
    let mut sum_brightness = 0;
    for (_, _, pixel) in img.pixels() {
        let brightness = pixel[0] as u32; // 对于灰度图像，只需获取一个颜色通道的值
        sum_brightness += brightness;
    }
    let avg_brightness = sum_brightness / (new_img.width() * new_img.height());
    println!("avg: {}", avg_brightness);

    // 定义调整因子
    let threshold_dark = 100; // 像素过黑的阈值
    let threshold_bright = 200; // 像素过亮的阈值
    let increase_factor = 80; // 增加的亮度值
    let decrease_factor = 20; // 减少的亮度值

    // 对每个像素进行调整
    for y in 0..img.height() {
        for x in 0..img.width() {
            let pixel = img.get_pixel(x, y);
            // println!("{} {} {} {}", pixel[0], pixel[1], pixel[2], pixel[3]);
            let r = pixel[0] as u32;
            let g = pixel[1];
            let b = pixel[2];
            let a = pixel[3];

            // 如果像素过黑，则调亮
            if r <= avg_brightness {
                let new_brightness = (r + avg_brightness  + increase_factor).min(255); // 确保不超过最大值 255
                let new_r = new_brightness as u8;
                // let new_g = new_brightness as u8;
                // let new_b = new_brightness as u8;
                new_img.put_pixel(x, y, Rgba([new_r, new_r, new_r, a]))
            } else if r > avg_brightness { // 如果像素过亮，则调暗
                let mut new_brightness = (r - decrease_factor).max(0); // 确保不小于最小值 0
                // if new_brightness < avg_brightness {
                //     new_brightness = avg_brightness + increase_factor
                // }
                let new_r = new_brightness as u8;
                let new_g = new_brightness as u8;
                let new_b = new_brightness as u8;
                new_img.put_pixel(x, y, Rgba([new_r, new_r, new_r, a]))
            } else {
                new_img.put_pixel(x, y, Rgba([r as u8, r as u8, r as u8, a]))
            }
        }
    }
    DynamicImage::from(new_img)
}

// 调整亮度的函数
fn adjust_brightness(img: &GrayImage, brightness: i32) -> GrayImage {
    // 创建一个新的图像，用于存储调整后的结果
    let mut new_img = img.clone();

    // 对每个像素进行调整
    for y in 0..img.height() {
        for x in 0..img.width() {
            // 获取像素的灰度值
            let mut pixel = img.get_pixel(x, y)[0] as i32;

            // 调整亮度
            pixel += brightness;

            // 确保像素值在 0 到 255 之间
            pixel = pixel.min(255).max(0);

            // 更新像素值
            new_img.put_pixel(x, y, image::Luma([pixel as u8]));
        }
    }

    new_img
}

/*fn adjust_brightness2() {
    let img = image::open("overexposure.jpg").expect("Failed to open image").to_luma8();

    let mut new_img = img.clone();

    let mut rust_data: Vec<i32> = Vec::new();
    let max = 0.9_f64;
    let min = 0.1_f64;

    for y in 0..img.height() {
        for x in 0..img.width() {
            // 获取像素的灰度值
            let pixel = img.get_pixel(x, y)[0] as i32;
            rust_data.push(pixel);
        }
    }

    rust_data.par_iter_mut().for_each(|entry|{
        let pixel = *entry;
        let alpha = (pixel >> 24) & 0xFF;
        // let red = ((pixel >> 16) & 0xFF) as f64 / 255f64.powf(gamma_i32) * 255.0;
        // let green = ((pixel >> 8) & 0xFF) as f64 / 255.0f64.powf(gamma_i32) * 255.0;
        let blue_pixel = (pixel & 0xFF) as f64;
        let mut blue = blue_pixel / 255.0f64.powf(max) * 255.0;
        if blue_pixel < 128f64 {
            blue = blue_pixel / 255.0f64.powf(min) * 255.0;
        }
        // let red_clamped = if red > 255.0 { 255 } else if red < 0.0 { 0 } else { red as i32 };
        // let green_clamped = if green > 255.0 { 255 } else if green < 0.0 { 0 } else { green as i32 };
        let blue_clamped = if blue > 255.0 { 255 } else if blue < 0.0 { 0 } else { blue as i32 };

        // Create the corrected pixel value
        let new_pixel = (alpha << 24) | (blue_clamped << 16) | (blue_clamped << 8) | blue_clamped;
        *entry = new_pixel
    });

    // 更新像素值
    // new_img.put_pixel(x, y, image::Luma([pixel as u8]));
}*/

fn adjust_brightness3(img: &GrayImage, brightness: i32) -> GrayImage {
    // 创建一个新的图像，用于存储调整后的结果
    let mut new_img = img.clone();

    let max = 0.8_f64;
    let min = 0.8_f64;

    // 对每个像素进行调整
    for y in 0..img.height() {
        for x in 0..img.width() {
            // 获取像素的灰度值
            let mut pixel = img.get_pixel(x, y)[0] as i32;

            let alpha = (pixel >> 24) & 0xFF;
            // let red = ((pixel >> 16) & 0xFF) as f64 / 255f64.powf(gamma_i32) * 255.0;
            // let green = ((pixel >> 8) & 0xFF) as f64 / 255.0f64.powf(gamma_i32) * 255.0;
            let blue_pixel = (pixel & 0xFF) as f64;
            let mut blue = blue_pixel / 255.0f64.powf(max) * 255.0;
            if blue_pixel < 128f64 {
                blue = blue_pixel / 255.0f64.powf(min) * 255.0;
            }
            // let red_clamped = if red > 255.0 { 255 } else if red < 0.0 { 0 } else { red as i32 };
            // let green_clamped = if green > 255.0 { 255 } else if green < 0.0 { 0 } else { green as i32 };
            let blue_clamped = if blue > 255.0 { 255 } else if blue < 0.0 { 0 } else { blue as i32 };

            // Create the corrected pixel value
            let new_pixel = (alpha << 24) | (blue_clamped << 16) | (blue_clamped << 8) | blue_clamped;

            // 更新像素值
            // 提取像素值的 R、G、B 分量
            let a = (new_pixel >> 24) as u8;
            let r = (new_pixel >> 16) as u8;
            let g = (new_pixel >> 8) as u8;
            let b = new_pixel as u8;
            new_img.put_pixel(x, y, image::Luma([new_pixel as u8]))
        }
    }

    new_img
}

// 压缩图片
fn compress_jpg(img_path: &str, quality: u8) -> anyhow::Result<Vec<u8>> {
    let img = image::open(img_path).unwrap();

    let mut buf = vec![];
    img.write_to(&mut Cursor::new(&mut buf), image::ImageFormat::Png)?;

    Ok(buf)
}
